import { createRoot, type Root } from 'react-dom/client';
import {
	qiankunWindow,
	renderWithQiankun,
	type QiankunProps
} from 'vite-plugin-qiankun/dist/helper';
import App from './App.tsx';

import { initGlobalStore } from '@/store/common/store';
import '@ant-design/v5-patch-for-react-19';
import './locales/index.ts';

import '@/assets/css/base.css';

let root: Root | null = null;

function render(props: QiankunProps) {
	const { container, ...args } = props;
	initGlobalStore(args);
	// React 18/19 的新 API
	root = createRoot(
		container ? container.querySelector('#root')! : document.querySelector('#root')!
	);
	root.render(<App {...args} />);
}

// qiankun 的生命周期钩子
renderWithQiankun({
	bootstrap() {
		console.log('React TS sub-app bootstraped');
	},
	mount(props) {
		console.log('React TS sub-app mount');
		render(props);
	},
	unmount() {
		console.log('React TS sub-app unmount');
		if (root) {
			// 使用 unmount API
			root.unmount();
			root = null;
		}
	},
	update(props) {
		console.log('React TS sub-app update');
		console.log(props);
	}
});

// 判断是否在 qiankun 环境下，用于独立开发运行
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
	render({});
}
